﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;
using Newtonsoft.Json;

namespace UI.Lib
{
    /// <summary>
    /// 公共的类，用于解析wcf页面传递过来的json字符串, 然后解析成一个对象
    /// </summary>
    public class CommonObject
    {
        private Hashtable _data;

        /// <summary>
        /// 根据json字符串，解析成一个HashTable
        /// </summary>
        /// <param name="str"></param>
        /// <returns>是否解析成功</returns>
        public bool SerializeObject(string str)
        {
            try
            {
                if (_data == null)
                {
                    _data = new Hashtable();
                }

                JavaScriptObject jsArray = JavaScriptConvert.DeserializeObject(str) as JavaScriptObject;
                object pValue = "";
                string key = "";
                if (jsArray != null)
                {
                    foreach (KeyValuePair<string, object> kvp in jsArray)
                    {
                        pValue = (null == kvp.Value) ? "" : kvp.Value;
                        key = kvp.Key.ToLower();
                        _data[key] = pValue;
                    }
                }

                return true;
            }
            catch { return false; }
        }

        /// <summary>
        /// 是否空数据
        /// </summary>
        public bool IsEmptyData
        {
            get { return this._data == null || this._data.Count == 0; }
        }

        /// <summary>
        /// 直接将json字符串反转成对象
        /// </summary>
        /// <param name="str"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        public object SerializeObject(string str, Type type)
        {
            return JavaScriptConvert.DeserializeObject(str, type);
        }

        /// <summary>
        /// 调用了SerializeObject 后取得反转出来的值
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public object GetValue(string key)
        {
            if (string.IsNullOrEmpty(key)) return null;
            return (this.IsEmptyData || !this._data.ContainsKey(key.ToLower())) ? null : this._data[key.ToLower()];
        }
    }
}
